﻿// ********************************************************************
//  文件名: ResableAdress.cs
//  描述:
//  作者: 胡宇辰
//  创建时间: 2024-4-18
// 
//  修改历史:
// ********************************************************************

using System.Net;
using System.Net.Sockets;
using System.Text;

namespace MyApp;

public class ReuseAddr
{
    public static void Start()
    {
        Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Console.WriteLine(serverSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress));
        try
        {
            serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6324));
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        serverSocket.Listen(10);
        Console.WriteLine("Server started");
        Socket clientSocket = serverSocket.Accept();
        string sendStr = "服务器发送";
        clientSocket.Send(Encoding.UTF8.GetBytes(sendStr));
        
        Thread.Sleep(3000);
        
        serverSocket.Close();
        Console.WriteLine("Server Close");
        
        Thread.Sleep(5000);

        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6324));
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        serverSocket.Listen(10);
        clientSocket = serverSocket.Accept();
        Console.WriteLine("Server started");
        sendStr = "服务器发送第二次";
        clientSocket.Send(Encoding.UTF8.GetBytes(sendStr));
        Thread.Sleep(1000);
        Console.WriteLine("结束");
    }
}